package com.ruoyi.system.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
        * 专用于SSO集成的HTTP客户端工具类
        * <p>
 * 这个工具类确保发送POST请求时，Content-Type被正确设置为 "application/json".
         * 避免修改若依框架自带的 HttpUtils, 保证代码隔离和项目整洁。
         * </p>
        */
public class SsoHttpUtils {

    private static final Logger log = LoggerFactory.getLogger(SsoHttpUtils.class);

    /**
     * 向指定 URL 发送POST方法的请求 (专门用于发送JSON数据)
     *
     * @param url   发送请求的 URL
     * @param jsonPayload  请求体，必须是JSON格式的字符串
     * @return 所代表远程资源的响应结果
     */
    public static String sendJsonPost(String url, String jsonPayload) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;

        try {
            log.info("SsoHttpUtils - 发送POST请求至: {}", url);
            log.info("SsoHttpUtils - 请求体: {}", jsonPayload);

            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();

            // 设置通用请求属性
            conn.setRequestProperty("accept", "application/json");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "RuoYi-SSO-Client/1.0");

            // --- 这是解决问题的核心代码 ---
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            // --------------------------------

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            // 设置连接和读取超时时间 (单位：毫秒)
            conn.setConnectTimeout(15000); // 15秒
            conn.setReadTimeout(15000);    // 15秒

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
            // 发送请求参数
            out.print(jsonPayload);
            // flush输出流的缓冲
            out.flush();

            // 获取响应码
            int responseCode = conn.getResponseCode();
            log.info("SsoHttpUtils - 收到响应码: {}", responseCode);

            // 根据响应码选择合适的输入流
            InputStreamReader inputStreamReader;
            if (responseCode >= 200 && responseCode < 300) {
                inputStreamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
            } else {
                inputStreamReader = new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8);
            }

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(inputStreamReader);
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }

            if (responseCode >= 400) {
                log.error("SsoHttpUtils - HTTP请求失败, 响应码: {}, 响应体: {}", responseCode, result.toString());
            } else {
                log.info("SsoHttpUtils - 收到响应体: {}", result.toString());
            }

        } catch (Exception e) {
            log.error("SsoHttpUtils - 发送POST请求出现异常, URL={}, 参数={}", url, jsonPayload, e);
            // 可以根据需要返回一个表示错误的JSON字符串，或者直接抛出异常
            return "{\"error\":true, \"message\":\"" + e.getMessage() + "\"}";
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception ex) {
                log.error("SsoHttpUtils -关闭流出现异常", ex);
            }
        }
        return result.toString();
    }
}
